import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useUserInfo } from './useInfoStore'
import { inserCart, findCart, DeleteCart } from '@/apis/Cart'
export const useCartStore = defineStore(
  'cartstore',
  () => {
    const CartList = ref([])
    const userinfo = useUserInfo()

    const addCartList = async (goods) => {
      const { skuId, count } = goods
      if (userinfo.userInfo.token) {
        //如果登录执行
        await inserCart({ skuId, count })
        const res = await findCart()
        CartList.value = res.result
      } else {
        //未登录执行
        //添加购物车操作
        //如果添加过 count +1
        //没有添加过则直接push
        //匹配skuid
        const item = CartList.value.find((item) => goods.skuId === item.skuId)
        if (item) {
          item.count++
        } else {
          CartList.value.push(goods)
        }
      }
    }

    //购物车单个删除功能
    const delCart = async (skuId) => {
      if (userinfo.userInfo.token) {
        //登录后的模块
        await DeleteCart([skuId])
        const res = await findCart()
        console.log('新的数据', res.result)
        CartList.value = res.result
      } else {
        //执行未登录本地模块
        CartList.value = CartList.value.filter((item) => item.skuId !== skuId)
      }
    }

    //单选状态属性设置(是否被选中)
    const changecheck = (skuId, selected) => {
      //通过传来的skuid进行查找，并且进行selected修改
      const item = CartList.value.find((item) => item.skuId == skuId)
      item.selected = selected
    }
    //全选框属性状态设置
    const allCheck = (selected) => {
      CartList.value.forEach((item) => (item.selected = selected))
    }
    //清空购物车操作
    const cleanCart = () => {
      CartList.value = []
    }

    //计算属性
    //1.总的数量  所有count之和
    const allCount = computed(() => CartList.value.reduce((a, c) => a + c.count, 0))
    //2.总价 总数*price
    const allPrice = computed(() => CartList.value.reduce((a, c) => a + c.count * c.price, 0))
    //全选状态设置isAll
    const isAll = computed(() => CartList.value.every((item) => item.selected))
    // .....计算已勾选商品的数量以及价格部分
    //过滤出勾选的商品
    const checkgoods = computed(() => CartList.value.filter((item) => item.selected === true))
    //计算勾选商品总数
    const checkNum = computed(() => checkgoods.value.reduce((a, c) => a + c.count, 0))
    //计算勾选商品的总价
    const checkPrice = computed(() => checkgoods.value.reduce((a, c) => a + c.count * c.price, 0))
    return {
      //购物车列表
      CartList,
      //添加删除购物车操作部分
      addCartList,
      delCart,
      //总数和总价部分
      allCount,
      allPrice,
      changecheck,
      //全选部分
      isAll,
      allCheck,
      //已选数量
      checkNum,
      //已选总价
      checkPrice,
      //清空购物车操作
      cleanCart,
    }
  },
  {
    persist: true,
  },
)
